import { Router } from 'express'
import { authMiddleware } from '../middlewares/auth'
import { validate } from '../middlewares/validate'
import { RoomService } from '../services/room/RoomService'

const router = Router()
const roomService = new RoomService()

// 创建房间
router.post('/', authMiddleware, validate('createRoom'), async (req, res) => {
  try {
    const room = await roomService.createRoom(req.user.userId, req.body)
    res.json({
      code: 200,
      message: '房间创建成功',
      data: room,
    })
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: error.message,
    })
  }
})

// 获取房间列表
router.get('/', async (req, res) => {
  try {
    const { page = 1, limit = 20, category } = req.query
    const rooms = await roomService.getRooms({
      page: Number(page),
      limit: Number(limit),
      category,
    })
    res.json({
      code: 200,
      message: '获取成功',
      data: rooms,
    })
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: error.message,
    })
  }
})

// 获取房间详情
router.get('/:roomId', async (req, res) => {
  try {
    const room = await roomService.getRoom(req.params.roomId)
    res.json({
      code: 200,
      message: '获取成功',
      data: room,
    })
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: error.message,
    })
  }
})

// 更新房间信息
router.put('/:roomId', authMiddleware, validate('updateRoom'), async (req, res) => {
  try {
    const room = await roomService.updateRoom(req.params.roomId, req.user.userId, req.body)
    res.json({
      code: 200,
      message: '更新成功',
      data: room,
    })
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: error.message,
    })
  }
})

export default router
